package study.SCADA网关解析;


import study.utils.ASCIITranslateUtils;

import java.io.UnsupportedEncodingException;

/**
 * @Author 刘伟涛
 * @Date 2024/8/14 9:29
 **/
public class HexToStringParser02 {

    public static void main(String[] args) {
        String hexString = "C4D0";
        findChineseCharacters(hexString);
    }

    public static void findChineseCharacters(String hexString) {
        byte[] bytes = hexStringToBytes(hexString);

        for (int i = 0; i < bytes.length - 1; i++) {
            int firstByte = bytes[i] & 0xFF;
            int secondByte = bytes[i + 1] & 0xFF;

            // 检查是否符合 GB2312/GBK 的汉字范围
            if (firstByte >= 0xB0 && firstByte <= 0xF7 && secondByte >= 0xA1 && secondByte <= 0xFE) {
                String chineseCharacter = null;
                try {
                    chineseCharacter = new String(new byte[]{(byte) firstByte, (byte) secondByte}, "GB2312");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                System.out.println("可能的汉字: " + chineseCharacter);
                i++; // 跳过下一个字节，因为已经处理过
            }
        }
    }

    public static byte[] hexStringToBytes(String hexString) {
        int len = hexString.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
                    + Character.digit(hexString.charAt(i+1), 16));
        }
        return data;
    }


}
